<template>
  <div class="main main-add-supply">
    <div class="part">
      <div class="p-title">
        <div class="title">新增自提点</div>
      </div>
      <div class="p-cont">
        <el-form
          :model="form"
          :rules="editType !== 'check' ? rules : null"
          label-width="220px"
          ref="ruleFormRef"
          readonly
        >
          <div class="sub-title">
            <el-divider content-position="left">基础信息</el-divider>
          </div>
          <el-form-item prop="name">
            <template #label
              >名称 <MyToolTip color="#606266" content="请填入自提点名称"
            /></template>
            <el-input
              v-model="form.name"
              placeholder="请输入自提点名称"
              :disabled="editType === 'check'"
            />
          </el-form-item>

          <el-form-item prop="agencyType">
            <template #label
              >联系地址 <MyToolTip color="#606266" content="请选择自提点类型。"
            /></template>
            <el-select v-model="form.agencyType" placeholder="请选择自提点类型">
              <el-option
                v-for="(item, index) in agencyTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="packageReceiver">
            <template #label
              >联系人
              <MyToolTip
                color="#606266"
                content="请填入联系人姓名，不超过50个汉字。"
            /></template>
            <el-input
              v-model="form.packageReceiver"
              placeholder="请输入联系人"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="phone" required>
            <template #label
              >联系电话
              <MyToolTip color="#606266" content="请填入联系人电话或手机号。"
            /></template>
            <el-input
              v-model="form.phone"
              placeholder="请输入联系电话"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="provinceId">
            <template #label
              >联系地址
              <MyToolTip color="#606266" content="请填地址，不超过100个汉字。"
            /></template>
            <myProCityArea
              @proCitySelectChange="proCitySelectChange"
              ref="myProCityAreaRef"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="street" required>
            <el-input
              v-model="form.street"
              placeholder="请填写详细地址"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="lonlat" required>
            <template #label
              >经纬度坐标
              <MyToolTip
                color="#606266"
                content="请填入实体药房的经纬度，用于进行物流调度服务。"
            /></template>
            <el-input
              v-model="form.lonlat"
              placeholder="经度,纬度"
              :disabled="editType === 'check'"
            />
            <div class="tip">
              <a
                target="_blank"
                href="https://api.map.baidu.com/lbsapi/getpoint/index.html"
                >点此使用百度坐标拾取工具</a
              >获取坐标数据
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import {
  getWarehousesById,
  createAndUpdateWarehouses,
  getAgentTypesApi
} from "@/api/supply";
import MyToolTip from "@/components/myToolTip.vue";
import myProCityArea from "@/components/myProCityArea.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";

const agencyTypeOptions = ref([]);

const userStore = useUserStoreHook();
const userRegions = userStore.userRegions;
const route = useRoute();
const router = useRouter();
const editType = ref<"add" | "edit" | "check">("check");
const editId = ref<string | number | null>(null);
const ruleFormRef = ref<FormInstance>(null);
const myProCityAreaRef = ref();
const supplyAreaRef = ref();
const expressList = [
  {
    value: 0,
    name: "自营配送"
  },
  {
    value: 1,
    name: "第三方-顺丰速运"
  },
  {
    value: 13,
    name: "第三方-京东快递"
  }
];

const form = ref({
  name: "",
  agencyType: "",
  packageReceiver: "",
  phone: "",
  provinceId: "",
  cityId: "",
  areaId: "",
  street: "",
  lonlat: "",
  longitude: "",
  latitude: "",
  warehouseId: "",
  deliveryDates: ""
});

const rules = reactive({
  name: [
    {
      required: true,
      message: "自提点名称不能为空,且长度不能超过50个汉字",
      trigger: "blur",
      min: 1,
      max: 50
    }
  ],
  agencyType: [
    {
      required: true,
      message: "自提点类型不能为空",
      trigger: "blur"
    }
  ],
  packageReceiver: [
    {
      required: true,
      message: "联系人不能为空,且长度不能超过50个汉字",
      trigger: "blur",
      min: 1,
      max: 50
    }
  ],
  phone: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
            value
          ) ||
          /^(0d{2,3})-?(d{7,8})$/.test(value)
        ) {
          callback();
        } else {
          callback(new Error("联系电话格式错误"));
        }
      }
    }
  ],

  provinceId: [
    {
      required: true,
      message: "省市区不能为空",
      trigger: "blur"
    }
  ],
  street: [
    {
      required: true,
      message: "街道地址不能为空,且长度不超过100",
      trigger: "blur",
      min: 1,
      max: 100
    }
  ],
  lonlat: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || !value.includes(",")) {
          callback(new Error("经纬度不能为空"));
          return;
        }
        const lonLatList = value.split(",");
        const lon = lonLatList[0];
        const lat = lonLatList[1];
        if (lonLatList.length !== 2 || !lonLatList[0] || !lonLatList[1]) {
          callback(new Error("经度和纬度之间请使用逗号分割，且只有1个逗号"));
        } else if (lon < -180 || lon > 180) {
          callback(new Error("经度范围错误，经度在-180到180之间"));
        } else if (lat < -90 || lat > 90) {
          callback(new Error("纬度范围错误，纬度在-90到90之间"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],

  warehouseId: [
    { required: true, trigger: "blur", message: "中心药房不能为空" }
  ],
  deliveryDates: [
    { required: true, trigger: "blur", message: "配送日期不能为空" }
  ]
});

function generateArea() {
  // console.log("userRegions:", userRegions);
  return userRegions.list.map(item => {
    const type = item.type;

    if (type === 2) {
      return {
        value: item.provinceId,
        label: item.provinceName,
        disabled: false
      };
    } else if (item.type === 3) {
      return {
        value: item.provinceId + "-" + item.cityId,
        label: item.provinceName + "-" + item.cityName,
        disabled: false
      };
    } else if (item.type === 4) {
      return {
        value: item.provinceId + "-" + item.cityId + "-" + item.areaId,
        label: item.provinceName + "-" + item.cityName + "-" + item.areaName,
        disabled: false
      };
    }
  });
}

function expressKindChange(value) {
  console.log("value:", value);
  form.value.distributors[0].expressKind = value;
  form.value.distributors[0].name = expressList.find(item => {
    return item.value === value;
  }).name;
  form.value.expressKind = value;
}

const supplyAreaList = ref(generateArea());

function proCitySelectChange(value) {
  form.value.provinceId = value[0];
  form.value.cityId = value[1];
  form.value.areaId = value[2];
}

function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }

  formEl.validate(async valid => {
    if (valid) {
      // if (lonLatList.length !== 2) {
      //       callback(new Error("经度和纬度之间请使用逗号分割，且只有1个逗号"));
      //     } else {
      //       callback();
      //     }
      // 经纬度坐标需要特殊处理
      const lonlat = form.value.lonlat.split(/,|，/);

      form.value.longitude = lonlat[0];
      form.value.latitude = lonlat[1];

      // 供应区域需要特殊处理
      form.value.supplyArea = form.value.mySupplyArea?.map(item => {
        const valueList = item.split("-");
        const checkedValue = valueList[valueList.length - 1];
        const target = userRegions.list.find(region => {
          return (
            region.provinceId === checkedValue ||
            region.cityId === checkedValue ||
            region.areaId === checkedValue
          );
        });
        return {
          type: target.type,
          provinceId: target.provinceId,
          provinceName: target.provinceName,
          cityId: target.cityId,
          cityName: target.cityName,
          areaId: target.areaId,
          areaName: target.areaName
        };
      });
      const submitForm = Object.assign({}, form.value);
      delete submitForm.lonlat;
      delete submitForm.mySupplyArea;
      delete submitForm.expressKind;
      delete submitForm.accountNo;
      delete submitForm.freight;
      console.log("submitForm:", submitForm);
      const res = await createAndUpdateWarehouses({
        userId: userStore.userInfo.user,
        data: JSON.stringify(submitForm)
      });
      const tip = editType.value === "add" ? "新增" : "更新";
      // res为null 不是undefined，说明新增成功过了
      if (res === null) {
        ElMessage({
          message: tip + "成功",
          type: "success"
        });
        router.push({ path: "/supply/index" });
      } else {
        ElMessage({
          message: tip + "失败",
          type: "error"
        });
      }
      console.log("submit!");
    } else {
      console.log("error submit!");
      return false;
    }
  });
}
function resetForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.resetFields();
}

async function getAgentType(): Promise<any> {
  const agentTypes = await getAgentTypesApi();
  console.log("agentTypes:", agentTypes);
  return agentTypes;
}

onBeforeMount(async () => {
  editId.value = route.query.id as string;
  editType.value = (route.query.type || "add") as "add" | "edit" | "check";
});
onMounted(async () => {
  // 获取自提点
  const agentTypes = await getAgentType();
  agencyTypeOptions.value = agentTypes.map(item => {
    return {
      value: item.id,
      label: item.name
    };
  });

  if (editType.value === "edit" || editType.value === "check") {
    form.value = await getWarehousesById(editId.value);
    // defaultAreaValue.value = [
    //   form.value.provinceId,
    //   form.value.cityId,
    //   form.value.areaId
    // ];
    // 处理经纬度
    if (form.value.longitude && form.value.latitude) {
      form.value.lonlat = form.value.longitude + "," + form.value.latitude;
    } else {
      form.value.lonlat = "";
    }
    // 处理省市区
    myProCityAreaRef.value.areaValue = [
      form.value.provinceId,
      form.value.cityId,
      form.value.areaId
    ];
    // 处理供应地区
    form.value.mySupplyArea = form.value.supplyArea?.map(item => {
      let value = "";
      if (item.provinceId) {
        value = item.provinceId;
      }
      if (item.cityId) {
        value += "-" + item.cityId;
      }
      if (item.areaId) {
        value += "-" + item.areaId;
      }
      return value;
    });
    // 处理配送地址
    form.value.expressKind = form.value.distributors[0].expressKind;
    form.value.freight = form.value.distributors[0].freight;
    form.value.accountNo = form.value.distributors[0].accountNo;
  }
});
</script>
<style>
.main-add-supply .el-divider__text {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.main-add-supply .el-divider__text span {
  margin: 0px 5px;
}

.main-add-supply .el-divider__text .question-icon {
  cursor: pointer;
}
</style>
<style scoped lang="scss">
.p-cont {
  .sub-title {
    margin: 60px auto;
  }

  .el-form-item {
    width: 700px;

    ::v-deep(.el-form-item__label) {
      display: flex;
      align-items: center;
    }

    .tip {
      cursor: pointer;

      a {
        color: blue;
      }
    }

    &.flex-inline {
      ::v-deep(.el-form-item__content) {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        // .express-num {
        //   margin-left: 20px;

        //   span {
        //     margin: auto 10px;
        //   }
        // }

        .el-input {
          width: 100px;
        }
      }
    }
  }
}
</style>
